<template>
  <div class="message-container">
    <div class="page-header">
      <h2>消息通知</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索消息内容"
          :prefix-icon="Search"
          class="search-input"
          clearable
        />
        <el-select v-model="typeFilter" placeholder="消息类型" class="filter-select">
          <el-option
            v-for="option in filterOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
    </div>

    <el-card class="message-card">
      <el-table 
        :data="filteredMessages" 
        style="width: 100%"
        :header-cell-style="{
          background: 'rgba(107, 155, 210, 0.1)',
          color: '#4a6fa5',
          fontWeight: '600'
        }"
      >
        <el-table-column prop="title" label="标题" width="180">
          <template #default="scope">
            <div class="message-title">
              <span class="title-icon">{{ getTitleIcon(scope.row.messageType) }}</span>
              <span>{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" />
        <el-table-column prop="createTime" label="时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              effect="light"
              class="status-tag"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="action-buttons">
              <template v-if="scope.row.messageType === 'SHARE_NOTE' && scope.row.status === 'PENDING'">
                <el-button 
                  type="success" 
                  size="small" 
                  @click="handleAcceptShare(scope.row)"
                >
                  接受
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleRejectShare(scope.row)"
                >
                  拒绝
                </el-button>
              </template>
              <el-button 
                v-if="scope.row.status === 'PENDING'"
                type="primary" 
                size="small" 
                @click="handleRead(scope.row)"
              >
                标记已读
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加笔记预览对话框 -->
    <el-dialog
      v-model="notePreviewDialog.visible"
      title="笔记预览"
      width="50%"
    >
      <div v-if="notePreviewDialog.note" class="note-preview">
        <h3>{{ notePreviewDialog.note.questionTitle }}</h3>
        <div class="note-content">{{ notePreviewDialog.note.content }}</div>
        <div class="note-meta">
          <span class="note-time">创建时间：{{ formatDate(notePreviewDialog.note.createTime) }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="notePreviewDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Search } from '@element-plus/icons-vue'
import { useUserStore } from '../../../store/UserStore'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserMessage',
  
  data() {
    return {
      messages: [],
      searchQuery: '',
      typeFilter: 'all',
      filterOptions: [
        { label: '全部', value: 'all' },
        { label: '系统通知', value: 'system' },
        { label: '学习提醒', value: 'study' },
        { label: '错题提醒', value: 'wrong' }
      ],
      notePreviewDialog: {
        visible: false,
        note: null,
        currentMessage: null
      },
      messageCache: new Map(),
      pollingInterval: null,
      maxRetries: 3,
      retryDelay: 2000
    }
  },

  computed: {
    userId() {
      return this.userStore.userInfo?.userId || null
    },
    isLoggedIn() {
      return this.userStore.isLoggedIn
    },
    filteredMessages() {
      return this.messages.filter(message => {
        const matchesSearch = message.content.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                           message.title.toLowerCase().includes(this.searchQuery.toLowerCase())
        
        if (this.typeFilter === 'all') {
          return matchesSearch
        }

        let matchesType = false
        const messageType = message.messageType

        switch (this.typeFilter) {
          case 'system':
            matchesType = (messageType === 'SYSTEM' || messageType === 'UPDATE' || messageType === 'SHARE_NOTE')
            break
          case 'study':
            matchesType = (messageType === 'STUDY' || messageType === 'SUGGESTION')
            break
          case 'wrong':
            matchesType = (messageType === 'WRONG')
            break
        }

        return matchesSearch && matchesType
      }).sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
    }
  },

  methods: {
    getMessageTitle(type) {
      const titles = {
        'SHARE_NOTE': '笔记分享',
        'SYSTEM': '系统通知',
        'STUDY': '学习提醒',
        'WRONG': '错题提醒',
        'UPDATE': '系统更新',
        'SUGGESTION': '学习建议'
      }
      return titles[type] || '通知'
    },

    getTitleIcon(type) {
      const icons = {
        'SHARE_NOTE': '📝',
        'SYSTEM': '🔔',
        'STUDY': '📚',
        'WRONG': '❌',
        'UPDATE': '🔄',
        'SUGGESTION': '💡'
      }
      return icons[type] || '📌'
    },

    async handleRead(message) {
      try {
        // 检查是否为合成消息（以synthetic_开头的ID）
        if (message.id && message.id.toString().startsWith('synthetic_')) {
          // 对于合成消息，只在前端更新状态
          const index = this.messages.findIndex(m => m.id === message.id);
          if (index !== -1) {
            this.messages[index].status = 'READ';
            this.messages[index].isRead = true;
            ElMessage.success('已标记为已读');
          }
          return;
        }
        
        // 对于真实消息，调用后端API
        if (!message.id) {
          ElMessage.error('消息ID不存在');
          return;
        }
        console.log('标记已读，消息ID:', message.id);
        
        await axios.put(`http://localhost:8080/api/messages/${message.id}/read`, null, {
          params: { userId: this.userId }
        });
        await this.loadAllMessages();
        ElMessage.success('已标记为已读');
      } catch (error) {
        console.error('标记消息已读失败:', error);
        ElMessage.error('标记已读失败');
      }
    },

    async fetchApiMessages(retryCount = 0) {
      try {
        const response = await axios.get('http://localhost:8080/api/messages/received', {
          params: { userId: this.userId }
        })
        if (response.data.code === 200) {
          const formattedMessages = response.data.data.map(msg => ({
            id: msg.messageId,
            title: msg.title || this.getMessageTitle(msg.messageType),
            content: msg.content,
            createTime: msg.createTime,
            messageType: msg.messageType,
            status: msg.status,
            isRead: msg.status === 'READ',
            noteId: msg.noteId,
            senderId: msg.senderId,
            noteTitle: msg.noteTitle
          }))
          return formattedMessages
        } else {
          console.error('获取API消息失败，响应数据格式不正确:', response.data)
          return []
        }
      } catch (error) {
        console.error('获取API消息失败:', error)
        if (retryCount < this.maxRetries) {
          console.log(`重试获取API消息 (${retryCount + 1}/${this.maxRetries})...`)
          await new Promise(resolve => setTimeout(resolve, this.retryDelay))
          return this.fetchApiMessages(retryCount + 1)
        } else {
          ElMessage.error('获取API消息失败，请稍后重试')
          return []
        }
      }
    },

    async fetchNearestSchedule() {
      if (!this.isLoggedIn || !this.userId) {
        console.log('用户未登录或ID无效，跳过获取日程')
        return null
      }

      try {
        console.log('开始获取最近日程，用户ID:', this.userId)
        const response = await axios.get(`http://localhost:8080/schedules/nearest/${this.userId}`)
        console.log('获取最近日程响应:', response.data)
        
        if (response.data && response.data.schedule) {
          const schedule = response.data.schedule
          const days = response.data.daysToNow
          console.log('解析到的日程信息:', {
            schedule,
            days,
            content: schedule?.content
          })
          
          if (schedule && schedule.content) {
            // 使用固定的合成ID格式
            const syntheticId = `synthetic_schedule_${schedule.scheduleId || Date.now()}`
            return {
              id: syntheticId,
              messageId: syntheticId,
              title: '学习提醒',
              content: `您有一个日程安排：${schedule.content}，距离现在还有${days}天`,
              createTime: new Date().toISOString(),
              messageType: 'STUDY',
              status: 'PENDING',
              isRead: false
            }
          }
        }
      } catch (error) {
        console.error('获取最近日程失败:', error)
        console.log('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        })
      }
      return null
    },

    async fetchWrongQuestionsCount() {
      if (!this.isLoggedIn || !this.userId) {
        console.log('用户未登录或ID无效，跳过获取错题')
        return null
      }

      try {
        console.log('开始获取错题数量，用户ID:', this.userId)
        const response = await axios.get(`http://localhost:8080/wrongquestions/count/byuser`, {
          params: {
            userId: this.userId
          }
        })
        console.log('获取错题数量响应:', response.data)
        
        if (response.data !== undefined && response.data !== null) {
          const count = parseInt(response.data)
          console.log('解析到的错题数量:', count)
          
          if (!isNaN(count) && count > 0) {
            // 使用固定的合成ID格式，添加时间戳确保唯一性
            const syntheticId = `synthetic_wrong_question_${Date.now()}`
            return {
              id: syntheticId,
              messageId: syntheticId,
              title: '错题提醒',
              content: `您有${count}道错题需要复习`,
              createTime: new Date().toISOString(),
              messageType: 'WRONG',
              status: 'PENDING',
              isRead: false
            }
          }
        }
      } catch (error) {
        console.error('获取错题数量失败:', error)
        console.log('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        })
      }
      return null
    },

    async loadAllMessages() {
      if (!this.isLoggedIn || !this.userId) {
        console.log('用户未登录或ID无效，不获取数据')
        this.messages = []
        return
      }
      console.log('开始加载所有消息...')

      const apiMessages = await this.fetchApiMessages()
      const scheduleMessage = await this.fetchNearestSchedule()
      const wrongQuestionMessage = await this.fetchWrongQuestionsCount()

      const allMessagesMap = new Map()

      // 保存当前消息的已读状态
      const currentMessagesStatus = new Map()
      this.messages.forEach(msg => {
        if (msg.id && msg.id.toString().startsWith('synthetic_')) {
          // 使用消息类型作为键，而不是ID的一部分
          currentMessagesStatus.set(msg.messageType, msg.status)
        }
      })

      apiMessages.forEach(msg => allMessagesMap.set(msg.id, msg))

      if (scheduleMessage) {
        // 检查是否有保存的状态
        if (currentMessagesStatus.has(scheduleMessage.messageType)) {
          scheduleMessage.status = currentMessagesStatus.get(scheduleMessage.messageType)
          scheduleMessage.isRead = scheduleMessage.status === 'READ'
        }
        allMessagesMap.set(scheduleMessage.id, scheduleMessage)
      }

      if (wrongQuestionMessage) {
        // 检查是否有保存的状态
        if (currentMessagesStatus.has(wrongQuestionMessage.messageType)) {
          wrongQuestionMessage.status = currentMessagesStatus.get(wrongQuestionMessage.messageType)
          wrongQuestionMessage.isRead = wrongQuestionMessage.status === 'READ'
        }
        allMessagesMap.set(wrongQuestionMessage.id, wrongQuestionMessage)
      }

      this.messages = Array.from(allMessagesMap.values())
      console.log('所有消息已加载:', this.messages)
    },

    startMessagePolling() {
      if (this.pollingInterval) return
      
      this.pollingInterval = setInterval(async () => {
        await this.loadAllMessages()
      }, 30000)
    },

    stopMessagePolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval)
        this.pollingInterval = null
      }
    },

    async handleAcceptShare(message) {
      try {
        if (!message.id) {
          ElMessage.error('消息ID不存在')
          return
        }
        console.log('接受分享，消息ID:', message.id)
        
        await axios.put(`http://localhost:8080/api/messages/${message.id}/status`, null, {
          params: {
            status: 'ACCEPTED',
            userId: this.userId
          }
        })

        if (message.noteId) {
          try {
            const noteResponse = await axios.get(`http://localhost:8080/api/notes/shared/${message.noteId}`, {
              params: {
                userId: this.userId
              }
            })

            if (noteResponse.data.code === 200) {
              const originalNote = noteResponse.data.data
              if (originalNote) {
                const createNoteResponse = await axios.post('http://localhost:8080/api/notes/createNote', {
                  userId: this.userId,
                  questionId: originalNote.questionId,
                  content: originalNote.content
                })
                
                if (createNoteResponse.data.code === 200) {
                  this.notePreviewDialog.note = {
                    questionTitle: originalNote.questionTitle || message.noteTitle || '笔记预览',
                    content: originalNote.content,
                    createTime: originalNote.createTime || new Date().toISOString()
                  }
                  this.notePreviewDialog.visible = true
                  ElMessage.success('笔记已成功添加到你的笔记列表')
                } else {
                  throw new Error('创建笔记失败')
                }
              } else {
                throw new Error('未找到原始笔记')
              }
            }
          } catch (noteError) {
            console.error('处理笔记失败:', noteError)
            ElMessage.error('笔记处理失败，请稍后重试')
          }
        }

        await this.loadAllMessages()
      } catch (error) {
        console.error('接受分享失败:', error)
        ElMessage.error('接受分享失败')
      }
    },

    async handleRejectShare(message) {
      try {
        if (!message.id) {
          ElMessage.error('消息ID不存在')
          return
        }
        console.log('拒绝分享，消息ID:', message.id)
        
        await axios.put(`http://localhost:8080/api/messages/${message.id}/status`, null, {
          params: {
            status: 'REJECTED',
            userId: this.userId
          }
        })

        ElMessage.success('已拒绝笔记分享')
        this.notePreviewDialog.visible = false
        await this.loadAllMessages()
      } catch (error) {
        console.error('拒绝分享失败:', error)
        ElMessage.error('拒绝分享失败')
      }
    },

    getStatusType(status) {
      const types = {
        'PENDING': 'warning',
        'READ': 'info',
        'ACCEPTED': 'success',
        'REJECTED': 'danger'
      }
      return types[status] || 'info'
    },

    getStatusText(status) {
      const texts = {
        'PENDING': '未读',
        'READ': '已读',
        'ACCEPTED': '已接受',
        'REJECTED': '已拒绝'
      }
      return texts[status] || '未知'
    },

    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }
  },

  created() {
    this.userStore = useUserStore()
  },

  mounted() {
    console.log('组件挂载，开始初始化数据')
    console.log('当前用户信息:', this.userStore.userInfo)
    console.log('用户登录状态:', this.isLoggedIn)
    console.log('用户ID:', this.userId)
    
    if (this.isLoggedIn && this.userId) {
      console.log('开始获取用户数据')
      this.loadAllMessages()
      this.startMessagePolling()
    } else {
      console.log('用户未登录或ID无效，不获取数据')
    }
    
    console.log('数据初始化完成，当前所有消息:', this.messages)
  },

  beforeUnmount() {
    this.stopMessagePolling()
  }
}
</script>

<style scoped>
.message-container {
  padding: 20px; /* 恢复水平内边距 */
  max-width: 1200px; /* 恢复最大宽度 */
  margin: 0 auto; /* 水平居中 */
  margin-top: 0 !important; /* 保留外部容器与顶部菜单衔接 */
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 恢复 ElCard 默认的 body 内边距 */
:deep(.el-card__body) {
  padding: 20px !important; /* 恢复 ElCard 默认的内边距 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 24px; /* 恢复水平内边距 */
}

.page-header h2 {
  color: #4a6fa5;
  font-size: 1.5rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.search-input {
  width: 240px;
}

.filter-select {
  width: 120px;
}

.message-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
}

.message-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4a6fa5;
}

.title-icon {
  font-size: 16px;
}

.status-tag {
  border-radius: 12px;
  padding: 2px 8px;
}

:deep(.el-table) {
  --el-table-border-color: rgba(107, 155, 210, 0.1);
  --el-table-header-bg-color: rgba(107, 155, 210, 0.1);
}

:deep(.el-table th) {
  font-weight: 600;
  color: #4a6fa5;
}

:deep(.el-table td) {
  color: #5a7ba8;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #6b9bd2, #8bb6e8);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a8bc1, #7aa5d7);
}

:deep(.el-button--primary:disabled) {
  background: #a8c5e8;
  transform: none;
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px rgba(107, 155, 210, 0.1);
}

:deep(.el-select .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.9);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 0 16px;
  }

  .header-actions {
    flex-direction: column;
  }

  .search-input,
  .filter-select {
    width: 100%;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

.note-preview {
  padding: 20px;
}

.note-preview h3 {
  color: #4a6fa5;
  margin-bottom: 16px;
}

.note-content {
  color: #5a7ba8;
  line-height: 1.6;
  white-space: pre-wrap;
}

.note-meta {
  margin-top: 16px;
  color: #8a9bb8;
  font-size: 0.9em;
}

.note-time {
  display: block;
  margin-top: 8px;
}

.status-tag {
  border-radius: 12px;
  padding: 2px 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border: none;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #56b32f, #74c050);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border: none;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #e45656, #e67878);
}
</style>
